package com.wolfword.crawler.client.listener;

import java.net.InetAddress;
import java.net.UnknownHostException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.boot.context.embedded.EmbeddedServletContainerInitializedEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationListener;

import com.wolfword.crawler.client.deal.StupidSpider;



public class ApplicationReady implements
		ApplicationListener<EmbeddedServletContainerInitializedEvent>,
		ApplicationContextAware {
	
	private static final Logger logger = LoggerFactory
			.getLogger(ApplicationReady.class);
	// Spring应用上下文环境
	private static ApplicationContext applicationContext;
	
	public static String hostAddress = null;//主机地址
	public static String hostName = null;//主机名称
	public static Integer hostPort = null;//主机端口

	@Override
	public void onApplicationEvent(EmbeddedServletContainerInitializedEvent event) {
	//public void onApplicationEvent(ApplicationReadyEvent event) {
		System.out.println("项目已经正常启动");
		if (hostAddress == null) {
			try {
				hostAddress = InetAddress.getLocalHost().getHostAddress();
				hostName = InetAddress.getLocalHost().getHostName();
			} catch (UnknownHostException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if (hostPort == null) {
			hostPort = event.getEmbeddedServletContainer().getPort();
		}
		//爬取网站
//		Crawler crawler = new Crawler();
//		crawler.crawlHtmls();
		new Thread(StupidSpider.getInstance()).start();
	}
	
	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		// TODO Auto-generated method stub

		ApplicationReady.applicationContext = applicationContext;
	}

	/**
	 * @return ApplicationContext
	 */
	public static ApplicationContext getApplicationContext() {
		return applicationContext;
	}

	/**
	 * 获取对象
	 * 
	 * @param name
	 * @return Object
	 * @throws BeansException
	 */
	public static Object getBean(String name) throws BeansException {
		logger.info("bean:" + name + "是否包含"
				+ applicationContext.containsBean(name) + "");
		Object o = applicationContext.getBean(name);
		if (o != null) {
			logger.info(o.getClass().getName());
		}
		return o;
	}

}